import { Client, Versions, type IFrame } from "@stomp/stompjs";
import SockJS from "sockjs-client";
import { ref } from "vue";
import { userStore } from "../../store/userStore";
import { ElMessage } from "element-plus";

let stompClient = ref<Client | null>(null);
let subscriptions = ref<any[]>([]); // 存储所有订阅

export function initWebSocket(token: string, messageCallback: any) {
    const socket = new SockJS("http://localhost:8080/stomp-endpoint");
    const userId = userStore().userInfo.uu_id;

    stompClient.value = new Client({
        stompVersions: new Versions(['1.2', '1.1', '1.0']),
        webSocketFactory: () => socket,
        connectHeaders: {
            Authorization: `Bearer ${token}`,
        },
        debug: (str) => {
            // 在这里过滤调试信息
            if (str.includes("ERROR") || str.includes("Close")) {
                console.log("Stomp" + str);
            }
        },

        reconnectDelay: 5000,
        heartbeatIncoming: 20000,
        heartbeatOutgoing: 20000,
        onConnect: () => {

            // 定义个人群组通知队列
            stompClient.value?.subscribe(`/user/queue/group-notifications`, (message) => {
                console.log(message.body);
            })
        },
        onStompError: (frame) => {
            console.error('Broker reported error: ' + frame.headers['message']);
            console.error('Additional details: ' + frame.body);
        }
    })

    stompClient.value.activate();

}

// 发送消息
export function sendStompMessage(destination: string, message: any) {
    if (stompClient.value && stompClient.value!.connected) {
        stompClient.value!.publish({
            destination: `/app/${destination}`,      // 注意：这里不要发送到app消息前缀，因为在后端接收后还要考虑是否发送给RabbitMQ
            // destination: destination,
            body: JSON.stringify(message),
            headers: { 'Content-type': 'application/json' }
        });
    } else {
        ElMessage.warning("异常了！!@@@@@")
    }
}

// 断开连接
export function disconnectStomp() {
    if (stompClient) {
        // 取消所有订阅
        subscriptions.value.forEach(sub => sub.unsubscribe());
        subscriptions.value = [];

        stompClient.value!.deactivate();
        console.log('Disconnected from WebSocket');
    }
}



